package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.*;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.OrderIdGenerator;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Override
    public Orders FindById(Integer id) {
        return orderMapper.FindById(id);
    }

    @Override
    public PageResult FindOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.PageQuery(ordersPageQueryDTO);
        long total = ordersPage.getTotal();
        List<Orders> records= ordersPage.getResult();
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(records);
        return pageResult;
    }

    @Override
    public OrderStatisticsVO GetStatistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        orderStatisticsVO.setConfirmed(orderMapper.GetStatistics(Orders.CONFIRMED));
        orderStatisticsVO.setToBeConfirmed(orderMapper.GetStatistics(Orders.TO_BE_CONFIRMED));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.GetStatistics(Orders.DELIVERY_IN_PROGRESS));

        return orderStatisticsVO;
    }

    @Override
    public void CompleteById(Integer id) {
        orderMapper.CompleteById(id);
    }

    @Override
    public void Cancel(OrdersCancelDTO ordersCancelDTO) {
        orderMapper.Cancel(ordersCancelDTO.getId(),ordersCancelDTO.getCancelReason());
    }

    @Override
    public void Rejection(OrdersRejectionDTO ordersCancelDTO) {
        orderMapper.Rejection(ordersCancelDTO.getId(),ordersCancelDTO.getRejectionReason());
    }

    @Override
    public void delivery(Integer id) {
        orderMapper.delivery(id);
    }

    @Override
    public void Confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(3)
                .build();
        orderMapper.Update(orders);

    }

    @Override
    public void cancelOrderById(Integer id) {
        orderMapper.cancelOrderById(id);
    }

    @Override
    public PageResult getPage(OrdersPageQueryDTO ordersPageQueryDTO, Long userId) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.PageQuery(ordersPageQueryDTO);
        List<Orders> ordersList = new ArrayList<>();

        ordersPage.getResult().forEach(orders -> {
            if (orders.getUserId()==userId){
                ordersList.add(orders);
            }
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(ordersList.size());
        pageResult.setRecords(ordersList);
        return pageResult;
    }

    @Override
    public void repetitionOrder(Integer id) {
        Orders orders =  orderMapper.FindById(id);
        if (orders!=null){
            orders.setId(null);
            orders.setStatus(Orders.PENDING_PAYMENT);
            orders.setNumber(null);
            orders.setOrderTime(LocalDateTime.now());
            orders.setCheckoutTime(null);
            orders.setPayMethod(null);
            orders.setPayStatus(Orders.UN_PAID);
            orders.setAmount(null);
            orders.setCancelReason(null);
            orders.setRejectionReason(null);
            orders.setCancelTime(null);
            orders.setEstimatedDeliveryTime(null);
            orders.setDeliveryStatus(0);
            orders.setDeliveryTime(null);
            orderMapper.addOrder(orders);
        }

    }


    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO, Long userId) {
        Orders orders = new Orders();
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        if (ordersSubmitDTO!=null){
            BeanUtils.copyProperties(ordersSubmitDTO,orders);

            orders.setUserId(userId);
            orders.setStatus(Orders.TO_BE_CONFIRMED);
            orders.setPayStatus(Orders.UN_PAID);
            //设置下单时间
            orders.setOrderTime(LocalDateTime.now());
            orderSubmitVO.setOrderTime(LocalDateTime.now());
            //设置订单号
             String number = OrderIdGenerator.generateOrderId();
            orders.setNumber(number);
            orderSubmitVO.setOrderNumber(number);
            //将订单保存数据库中
            orderMapper.addOrder(orders);
            //设置订单金额
            BigDecimal bigDecimal = BigDecimal.valueOf(orders.getPackAmount());
            orderSubmitVO.setOrderAmount(bigDecimal.add(orders.getAmount()));
            //设置订单ID
            orderSubmitVO.setId(orderMapper.FindId(number));
        }

        return orderSubmitVO;
    }
//
    @Override
    public LocalDateTime payment(OrdersPaymentDTO ordersPaymentDTO) {
        Integer orderId = Math.toIntExact(orderMapper.FindId(ordersPaymentDTO.getOrderNumber()));
        Orders orders = orderMapper.FindById(orderId);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayStatus(2);
        orders.setStatus(2);
        orderMapper.Update(orders);
        return orders.getEstimatedDeliveryTime();
    }
}
